package com.ruoyi.property.service.impl;

import java.math.BigDecimal;
import java.sql.Time;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.property.mapper.MeterReadingMapper;
import com.ruoyi.property.domain.MeterReading;
import com.ruoyi.property.service.IMeterReadingService;
import com.ruoyi.common.core.text.Convert;

import javax.validation.constraints.NotNull;

/**
 * 抄表信息Service业务层处理
 * 
 * @author sux
 * @date 2021-07-01
 */
@Service
public class MeterReadingServiceImpl implements IMeterReadingService {
    @Autowired
    private MeterReadingMapper meterReadingMapper;

    /**
     * 查询抄表信息
     * 
     * @param meterId 抄表信息ID
     * @return 抄表信息
     */
    @Override
    public MeterReading selectMeterReadingById(Long meterId)
    {
        return meterReadingMapper.selectMeterReadingById(meterId);
    }

    /**
     * 查询抄表信息列表
     * 
     * @param meterReading 抄表信息
     * @return 抄表信息
     */
    @Override
    public List<MeterReading> selectMeterReadingList(MeterReading meterReading)
    {
        return meterReadingMapper.selectMeterReadingList(meterReading);
    }

    /**
     * 新增抄表信息
     * 
     * @param meterReading 抄表信息
     * @return 结果
     */
    @Override
    public int insertMeterReading(MeterReading meterReading) {
        //获取表类型
        String meterType = meterReading.getMeterType();
        //获取表对象名
        String meterName = meterReading.getMeterName();
        //获取本期度数
        BigDecimal curDegrees = meterReading.getCurDegrees();
        //获取抄表年月
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(meterReading.getCurTime());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;

        //根据表类型和表名查找记录
        MeterReading reading = new MeterReading();
        reading.setMeterType(meterType);
        reading.setMeterName(meterName);
        List<MeterReading> meterReadings = selectMeterReadingList(reading);

        if(meterReadings!=null&&!meterReadings.isEmpty()) {
            //判断本月是否已存在记录
            for (int i = 0; i < meterReadings.size(); i++) {
                calendar.setTime(meterReadings.get(i).getCurTime());
                int year2 = calendar.get(Calendar.YEAR);
                int month2 = calendar.get(Calendar.MONTH)+1;
                if (year==year2&&month == month2) {
                    throw new BaseException(meterReadings.get(i).getMeterName()+"表"+year2+"年"+month2+"月"+"已抄表");
                }
            }
            //
            for (int j = 0; j < meterReadings.size(); j++) {
                calendar.setTime(meterReadings.get(j).getCurTime());
                int year3 = calendar.get(Calendar.YEAR);
                int month3 = calendar.get(Calendar.MONTH)+1;
                if((year==year3&&month==month3+1)||(year==year3+1&&month==1&&month3==12)){
                    meterReading.setPriorTime(meterReadings.get(j).getCurTime());
                    //上期度数大于本期度数报错
                    if (curDegrees.compareTo(meterReadings.get(j).getCurDegrees()) == -1 ){
                        throw new BaseException("抄表度数错误");
                    }
                    meterReading.setPriorDegrees(meterReadings.get(j).getCurDegrees());
                    break;
                }
            }
            //判断上期度数或者上期抄表时间是否为空
            BigDecimal priorDegrees = meterReading.getPriorDegrees();
            Date priorTime = meterReading.getPriorTime();
            if(priorDegrees==null||priorTime ==null){
            throw new BaseException("抄表度数或时间错误");
           }
        }else {
            meterReading.setPriorDegrees(BigDecimal.valueOf(0));
        }
        //添加创建时间
        meterReading.setCreateTime(DateUtils.getNowDate());
        return meterReadingMapper.insertMeterReading(meterReading);
    }

    /**
     * 修改抄表信息
     * 
     * @param meterReading 抄表信息
     * @return 结果
     */
    @Override
    public int updateMeterReading(MeterReading meterReading){

        //没有表ID时，根据表类型，表名，抄表时间查找ID
        if(meterReading.getMeterId()==null||"".equals(meterReading.getMeterId())){
            String meterType = meterReading.getMeterType();
            String meterName = meterReading.getMeterName();
            Date curTime = meterReading.getCurTime();
            List<MeterReading> meterReadingList = selectMeterReadingList(meterReading);
            if (meterReadingList!=null&&!meterReadingList.isEmpty()){
                for (int i = 0; i < meterReadingList.size(); i++) {
                    if (meterType.equals(meterReadingList.get(i).getMeterType())&&meterName.equals(meterReadingList.get(i).getMeterName())&&sameDate(curTime, meterReadingList.get(i).getCurTime())) {
                        meterReading.setMeterId(meterReadingList.get(0).getMeterId());
                        break;
                    }
                }
                if(meterReading.getMeterId()==null||"".equals(meterReading.getMeterId())){
                    throw new BaseException("没有可更新的记录");
                }
                return meterReadingMapper.updateMeterReading(meterReading);
            }else {
                throw new BaseException("没有可更新的记录");
            }
        }

        return meterReadingMapper.updateMeterReading(meterReading);
    }

    /**
     * 删除抄表信息对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteMeterReadingByIds(String ids){
        return meterReadingMapper.deleteMeterReadingByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除抄表信息信息
     * 
     * @param meterId 抄表信息ID
     * @return 结果
     */
    @Override
    public int deleteMeterReadingById(Long meterId) {
        return meterReadingMapper.deleteMeterReadingById(meterId);
    }

    /**
     * 导入抄表信息
     * @param meterReadingList
     * @param updateSupport
     * @return
     */
    @Override
    public String importMeterReading(List<MeterReading> meterReadingList, boolean updateSupport) {
        if(updateSupport) {
            for (int i = 0; i < meterReadingList.size(); i++) {

                if (isExcite(meterReadingList.get(i))) {
                    updateMeterReading(meterReadingList.get(i));
                } else {
                    insertMeterReading(meterReadingList.get(i));
                }
            }
        }else {
            for (int i = 0; i < meterReadingList.size(); i++) {
                insertMeterReading(meterReadingList.get(i));
            }
        }
        return "导入成功";
    }

    /**
     * 没有ID时判断抄表记录是否已存在
     * @param meterReading
     * @return
     */
    public boolean isExcite(MeterReading meterReading){
        String meterType = meterReading.getMeterType();
        String meterName = meterReading.getMeterName();
        Date curTime = meterReading.getCurTime();
        List<MeterReading> meterReadingList = selectMeterReadingList(meterReading);
            if (meterReadingList!=null&&!meterReadingList.isEmpty()){
                for (int i = 0; i < meterReadingList.size(); i++) {
                    if (meterType.equals(meterReadingList.get(i).getMeterType())&&meterName.equals(meterReadingList.get(i).getMeterName())&& sameDate(curTime, meterReadingList.get(i).getCurTime())) {
                        return true;
                    }
                }
            }
        return false;
    }
    /**
     * 判断两个日期是否同一天
     * @param date1
     * @param date2
     * @return
     */
    private static boolean sameDate(Date date1, Date date2) {
        LocalDate localDate1 = ZonedDateTime.ofInstant(date1.toInstant(), ZoneId.systemDefault()).toLocalDate();
        LocalDate localDate2 = ZonedDateTime.ofInstant(date2.toInstant(), ZoneId.systemDefault()).toLocalDate();
        return localDate1.isEqual(localDate2);
    }
}
